/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2015
 */

package com.jzwl.system.admin.sysuser.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jzwl.system.admin.dictype.service.DicTypeService;
import com.jzwl.system.admin.sysuser.service.*;
import com.jzwl.system.admin.user.pojo.BusyShopuser;
import com.jzwl.system.base.controller.BaseController;
import com.jzwl.common.constant.GlobalConstant;
import com.jzwl.common.md5.AuthUtils;
import com.jzwl.common.page.PageObject;
import com.jzwl.common.utils.JsonTool;
import com.jzwl.common.utils.StringUtil;

/**
 * Sysuser Sysuser sysuser
 * <p>
 * Title:SysuserController
 * </p>
 * <p>
 * Description:Sysuser
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author aotu-code
 */
@Controller("v2sysuserController")
@RequestMapping("/v2sysuser")
public class SysuserController extends BaseController {

	@Autowired
	private SysuserService sysuserService;
	@Autowired
	private DicTypeService dicTypeService;

	/**
	 * 跳转到添加页面
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toAddUser")
	public String toAddUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		/*// 加载城市下拉框数据
		List<Map<String, Object>> cityList = dicTypeService.queryData("zone");
		// 加载性别下拉框数据
		List<Map<String, Object>> sexList = dicTypeService.queryData("dic_sex");
		model.addAttribute("cityList", cityList);
		model.addAttribute("sexList", sexList);*/
		model.addAttribute("url", "v2sysuser/addSysuser.html");
		return "/base/system/userform";
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toUpdatePwd")
	public String toUpdatePwd(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		model.addAttribute("id", request.getParameter("id"));
		return "/base/system/changepwdform";
	}

	/**
	 * 跳转到修改页面
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toUpdateUser")
	public String toUpdateUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);
		try {
			/*// 加载城市下拉框数据
			List<Map<String, Object>> cityList = dicTypeService
					.queryData("zone");
			// 加载性别下拉框数据
			List<Map<String, Object>> sexList = dicTypeService
					.queryData("dic_sex");*/
			// 根据id获取数据
			Map<String, Object> objMap = sysuserService.getSysuser(paramsMap);
			/*model.addAttribute("cityList", cityList);
			model.addAttribute("sexList", sexList);*/
			model.addAttribute("objMap", objMap);
			model.addAttribute("disabled", "disabled='disabled'");
			model.addAttribute("style", "style='display:none'");
			model.addAttribute("url", "v2sysuser/updateSysuser.html");
			return "/base/system/userform";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "获取数据失败");
			return "/error";
		}
	}

	/**
	 * 添加或修改
	 * 
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value = "/addSysuser", method = RequestMethod.POST)
	public String sysuser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);
		paramsMap.put("isDelete", 0);// 默认未删除
		paramsMap.put("createdTime", new Date());
		String password = paramsMap.get("password").toString();
		paramsMap.put("password", AuthUtils.getPassword(password));// md5加密
		// 暂时为用到
		paramsMap.put("wxId", null);
		paramsMap.put("openId", null);

		try {
			boolean isUserLive = sysuserService.isUserLive(paramsMap.get(
					"username").toString());
			if (!isUserLive) {
				model.addAttribute("msg", "该用户已存在");
				return "/error";
			} else {
				boolean flag = sysuserService.addSysuser(paramsMap);
				if (flag) {
					return "redirect:/v2sysuser/sysuserList.html?start=0";
				} else {
					model.addAttribute("msg", "添加失败");
					return "/error";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "添加失败");
			return "/error";
		}
	}

	/**
	 * sysuserlist
	 */
	@RequestMapping(value = "/sysuserList")
	public String sysuserList(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);
		PageObject po = new PageObject();
		paramsMap.put("isDelete", 0);
		try {
			po = sysuserService.querySysuserList(paramsMap);
			model.addAttribute("po", po);
			model.addAttribute("paramsMap", paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "获取数据失败");
			return "/error";
		}
		return "/base/system/userlist";
	}

	/**
	 * 修改sysuser
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateSysuser", method = RequestMethod.POST)
	public String updateSysuser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);
		// 暂时为用到
		paramsMap.put("wxId", null);
		paramsMap.put("openId", null);

		try {

			boolean flag = sysuserService.updateSysuser(paramsMap);

			if (flag) {
				return "redirect:/v2sysuser/sysuserList.html?start=0";
			} else {
				model.addAttribute("msg", "保存失败");
				return "/error";
			}
		} catch (Exception e) {

			e.printStackTrace();
			model.addAttribute("msg", "保存失败");
			return "/error";
		}
	}

	/**
	 * 修改sysuser密码,管理员修改密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	public String updatePwd(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		// createParameterMap(request);

		createParameterMap(request);
		String password = paramsMap.get("password").toString();
		paramsMap.put("password", AuthUtils.getPassword(password));// md5加密
		try {

			boolean flag = sysuserService.updatePasswordSysuser(paramsMap);

			if (flag) {
				return "redirect:/v2sysuser/sysuserList.html?start=0";
			} else {
				model.addAttribute("msg", "保存失败");
				return "/error";
			}
		} catch (Exception e) {

			e.printStackTrace();
			model.addAttribute("msg", "保存失败");
			return "/error";
		}
	}

	/**
	 * 用户自己修改密码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updatePwdByUser", method = RequestMethod.POST)
	public String updatePwdByUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		// createParameterMap(request);
		createParameterMap(request);
		String password = paramsMap.get("password1").toString();
		paramsMap.put("password", AuthUtils.getPassword(password));// md5加密
		try {

			boolean flag = sysuserService.updatePasswordSysuser(paramsMap);

			if (flag) {

				return "/base/system/updatePasswordSuccess";

				// return "redirect:/login/exit.html";

			} else {

				JsonTool.printMsg(response, "保存失败！", flag);
				return "/error";

			}
		} catch (Exception e) {

			e.printStackTrace();

			JsonTool.printMsg(response, "保存失败！", false);
			return "/error";

		}

	}

	/**
	 * 删除sysuser
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/deleteSysuser")
	public String deleteSysuser(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);

		try {

			boolean flag = sysuserService.deleteSysuser(paramsMap);

			if (flag) {
				return "redirect:/v2sysuser/sysuserList.html?start=0";
			} else {
				model.addAttribute("msg", "删除失败");
				return "/error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "删除失败");
			return "/error";
		}

	}

	// aaaaaa
	/**
	 * 根据id获取单个用户的信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysuser", method = RequestMethod.POST)
	public Map<String, Object> getSysuser(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("111");
		Map<String, Object> resultMap = new HashMap<String, Object>();

		createParameterMap(request);

		try {

			Map<String, Object> map = sysuserService.getSysuser(paramsMap);
			resultMap.put("success", true);
			resultMap.put("data", map);

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("success", false);
			resultMap.put("data", null);
		}

		String oldPassword = paramsMap.get("oldPassword").toString();
		System.out.println(oldPassword);
		paramsMap.put("oldPassword", AuthUtils.getPassword(oldPassword));// md5加密
		String newPassword = AuthUtils.getPassword(oldPassword);

		String username = request.getSession().getAttribute("userName") + "";
		paramsMap.put("username", username);
		return resultMap;
	}

	/**
	 * 修改sysuser
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public void updatePassWordSysuser(HttpServletRequest request,
			HttpServletResponse response) {

		createParameterMap(request);

		String password = paramsMap.get("password").toString();
		paramsMap.put("password", AuthUtils.getPassword(password));// md5加密

		try {

			boolean flag = sysuserService.updatePasswordSysuser(paramsMap);

			if (flag) {

				JsonTool.printMsg(response, "重置成功！", flag);
			} else {

				JsonTool.printMsg(response, "重置失败！", flag);
			}
		} catch (Exception e) {

			e.printStackTrace();

			JsonTool.printMsg(response, "重置失败！", false);
		}

	}

	/**
	 * sysuserlist
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Map<String, Object> login(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		createParameterMap(request);

		String password = String.valueOf(paramsMap.get("password"));
		password = AuthUtils.MD5(password);
		paramsMap.put("password", password);

		// PageObject po = new PageObject();
		boolean flag = false;

		try {
			List<Map<String, Object>> permissionList = new ArrayList<Map<String, Object>>();
			Map<String, Object> userMap = sysuserService.queryUser(paramsMap);
			if (null != userMap && !userMap.isEmpty()) {
				flag = true;
				// 查询当前用户的角色权限信息
				// permissionList =
				// sysuserService.queryRoleResourceList(String.valueOf(userMap.get("roleId")));
				// 把用户信息放入session中
				request.getSession().setAttribute("userId",
						userMap.get("userId"));
			}

			if (!flag) {
				resultMap.put("message", "登录异常");
			}
			resultMap.put("success", flag);
			resultMap.put("userinfo", userMap);
			resultMap.put("permissionList", permissionList);

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("success", false);
			resultMap.put("userinfo", null);
		}

		return resultMap;
	}

	/**
	 * sysuserlist
	 */
	@RequestMapping(value = "/loginSkip", method = RequestMethod.GET)
	public ModelAndView loginSkip(HttpServletRequest request,
			HttpServletResponse response) {

		ModelAndView mv = new ModelAndView();
		String name = GlobalConstant.getCurrentUserName();
		if (StringUtil.isEmptyOrBlank(name)) {
			request.setAttribute("msg", "登陆失败！请重新登陆！");
			mv.addObject("msg", "登陆失败！请重新登陆！");
			mv.setViewName("/error");
			return mv;
		}
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		try {
			userList = sysuserService.queryUserByName(name);
			if (userList == null || userList.size() == 0) {
				request.setAttribute("msg", "登陆失败！请重新登陆！");
				mv.addObject("msg", "登陆失败！请重新登陆！");
				mv.setViewName("/error");
				return mv;
			}
		} catch (Exception e) {
			request.setAttribute("msg", "登陆失败！请重新登陆！");
			mv.addObject("msg", "登陆失败！请重新登陆！");
			mv.setViewName("/error");
			return mv;
		}
		// url = "redirect:/image/pageImage.html";
		mv.setViewName("redirect:/index/index.html");
		// 把用户信息放入session中
		request.getSession().setAttribute("userId",
				userList.get(0).get("userId"));
		request.getSession().setAttribute("userinfo", userList.get(0));

		return mv;
	}

	/**
	 * 加载用户的权限信息用以控制前台菜单的显示
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/authority", method = RequestMethod.POST)
	public Map<String, Object> queryAuthority(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		List<Map<String, Object>> permissionList = new ArrayList<Map<String, Object>>();

		try {
			// 查询当前用户的角色权限信息

			permissionList = sysuserService.queryUserResourceList(String
					.valueOf(request.getSession().getAttribute("userId")));
			if (permissionList.size() > 0) {
				resultMap.put("success", true);
			} else {
				resultMap.put("success", false);
			}
			resultMap.put("permissionList", permissionList);

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("success", false);
			resultMap.put("permissionList", permissionList);
		}

		return resultMap;
	}

	/**
	 * 查询用户所在城市的以选择的店铺
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryCityInShopList", method = RequestMethod.POST)
	public Map<String, Object> queryCityInShopList(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		PageObject po = new PageObject();

		// paramsMap.put("shopclassId", 1);
		createParameterMap(request);

		try {

			po = sysuserService.queryCityInShopList(paramsMap);

			resultMap.put("list", po.getDatasource());

			resultMap.put("totalProperty", po.getTotalCount());

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("list", po.getDatasource());

			resultMap.put("totalProperty", po.getTotalCount());

		}

		return resultMap;
	}

	/**
	 * 查询用户所在城市的未选择的店铺
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryNoCityShopList", method = RequestMethod.POST)
	public Map<String, Object> queryNoCityShopList(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		PageObject po = new PageObject();

		createParameterMap(request);

		try {

			po = sysuserService.queryNoCityShopList(paramsMap);

			resultMap.put("list", po.getDatasource());

			resultMap.put("totalProperty", po.getTotalCount());

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("list", po.getDatasource());

			resultMap.put("totalProperty", po.getTotalCount());

		}

		return resultMap;
	}

	/**
	 * 添加店铺用户对应关系
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addShopToUser", method = RequestMethod.POST)
	public Map<String, Object> addShopToUser(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		createParameterMap(request);

		try {
			// 查询当前用户所属的角色
			Map<String, Object> map = sysuserService.queryUserRole(paramsMap);
			String roleId = String.valueOf(map.get("roleId"));
			boolean flag = false;

			if ("63".equals(roleId)) {
				flag = sysuserService.addShopToUserDZ(paramsMap);
			} else {
				flag = sysuserService.addShopToUser(paramsMap);
			}

			if (flag) {

				resultMap.put("success", true);
				resultMap.put("info", "添加成功！");
			} else {

				resultMap.put("info", "添加失败！");
			}

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("info", "添加失败!");
		}

		return resultMap;

	}

	/**
	 * 删除店铺用户对应关系
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteShopToUser", method = RequestMethod.POST)
	public Map<String, Object> deleteShopToUser(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		createParameterMap(request);

		try {

			boolean flag = sysuserService.deleteShopToUser(paramsMap);

			if (flag) {

				resultMap.put("success", true);
				resultMap.put("info", "删除成功！");
			} else {

				resultMap.put("info", "删除失败！");
			}

		} catch (Exception e) {

			e.printStackTrace();

			resultMap.put("info", "删除失败!");
		}

		return resultMap;

	}

	/**
	 * 判断当前用户下是否已经分配店铺
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryUserShop", method = RequestMethod.POST)
	public Map<String, Object> queryUserShop(HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		createParameterMap(request);

		try {

			List<Map<String, Object>> list = sysuserService
					.queryUserShop(paramsMap);

			if (null != list && list.size() > 0) {

				resultMap.put("success", true);
				resultMap.put("flag", 1);
				resultMap.put("info", "已经分配店铺");
			} else if (null != list && list.size() == 0) {
				resultMap.put("success", true);
				resultMap.put("flag", 2);
				resultMap.put("info", "未分配店铺");
			}

		} catch (Exception e) {

			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("flag", 0);
			resultMap.put("info", "操作失败!");
		}

		return resultMap;

	}

	/**
	 * 查询用户已拥有角色
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sysroleUserList", method = RequestMethod.POST)
	public Map<String, Object> sysroleUserList(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		createParameterMap(request);
		PageObject po = new PageObject();
		try {
			po = sysuserService.querySysroleUserList(paramsMap);
			resultMap.put("list", po.getDatasource());
			resultMap.put("totalProperty", po.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("list", po.getDatasource());
			resultMap.put("totalProperty", po.getTotalCount());
		}
		return resultMap;
	}

	/**
	 * 查询用户未拥有角色
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sysroleNoUserList", method = RequestMethod.POST)
	public Map<String, Object> sysroleNoUserList(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		createParameterMap(request);
		PageObject po = new PageObject();
		try {
			po = sysuserService.querySysroleNoUserList(paramsMap);
			resultMap.put("list", po.getDatasource());
			resultMap.put("totalProperty", po.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("list", po.getDatasource());
			resultMap.put("totalProperty", po.getTotalCount());
		}
		return resultMap;
	}

	/**
	 * 删除sysrole
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteSysroleUser", method = RequestMethod.POST)
	public Map<String, Object> deleteSysroleUser(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		createParameterMap(request);
		try {
			boolean flag = sysuserService.deleteSysroleUser(paramsMap);
			if (flag) {
				resultMap.put("success", true);
				resultMap.put("info", "删除成功！");
			} else {
				resultMap.put("info", "删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("info", "删除失败！");
		}
		return resultMap;
	}

	/**
	 * 添加角色下的用户
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addSysroleUser", method = RequestMethod.POST)
	public Map<String, Object> addSysroleUser(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		createParameterMap(request);
		paramsMap.put("createdTime", new Date());
		try {
			boolean flag = sysuserService.addSysroleUser(paramsMap);
			if (flag) {
				resultMap.put("success", true);
				resultMap.put("info", "添加成功！");
			} else {
				resultMap.put("info", "添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("info", "添加失败!");
		}
		return resultMap;
	}

	/**
	 * 从数据库查询出密码和从前台ajax传过来的密码进行比较 相等返回yes
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkPassword", method = RequestMethod.POST)
	public String ckpassword(HttpServletRequest request,
			HttpServletResponse response) {
		String str = "";
		String id = request.getParameter("id");
		String password = request.getParameter("oldPassword");
		String password1 = AuthUtils.getPassword(password);// md5加密
		paramsMap.put("password", password1);
		paramsMap.put("id", id);
		Map<String, Object> map = sysuserService.getSysuser(paramsMap);
		if (password1.equals(map.get("password"))) {
			str = "yes";
		} else {
			str = "no";
		}
		return str;
	}

}
